package com.zs.games.config;

import com.zs.games.resultTool.ResultCodeEnum;
import com.zs.games.exception.APIException;
import com.zs.games.utils.JwtTokenUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 
 * @date 2023年05月09日 15:22
 */
@Configuration
@Slf4j
public class UserLoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object handler) throws Exception {
        //此处为不需要登录的接口放行
        String requestURI = arg0.getRequestURI();
        String method = arg0.getMethod();
        if (method.equals("OPTIONS") || requestURI.contains("/login")
                || requestURI.contains("/register") || requestURI.contains("/error")
                || requestURI.contains("/upload/*")
        ) {
            return true;
        } else {
            //验证token
            final String headerToken = arg0.getHeader("token");
            arg1.setContentType("text/html;charset=utf-8");
            //判断请求信息
            if (StringUtils.isBlank(headerToken) || JwtTokenUtils.isTokenExpired(headerToken)) {
                log.error("token为空或过期");
                throw new APIException(ResultCodeEnum.TOKEN_ERR);
            }
            return true;

        }

    }


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
